package com.qst.order.controller;

import com.qst.order.domain.DTO.LoginReq;
import com.qst.order.domain.DTO.LoginResp;
import com.qst.order.domain.DTO.UpdatePasswordDTO;
import com.qst.order.domain.User;
import com.qst.order.service.UserService;
import com.qst.order.utils.JwtUtil;
import com.qst.order.utils.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserService userService;

    private final PasswordEncoder passwordEncoder;

    @Autowired
    private  JwtUtil jwtUtil;

    /**
     * 登录
     * @param req
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginReq req){

        User user= userService.findByUsername(req.getUsername());
        if (user==null){
            return Result.error("用户不存在");
        }
        if (!passwordEncoder.matches(req.getPassword(),user.getPassword())){
            return Result.error("密码错误");
        }
        if(!(req.getRole() == user.getRole())){
            return Result.error("用户角色错误");
        }
        if (user.getStatus()==0){
            return Result.error("用户被禁用");
        }
        String token = jwtUtil.generateToken(String.valueOf(user.getId()), user.getUsername());
        LoginResp loginResp = new LoginResp();
        loginResp.setRole(user.getRole());
        loginResp.setUsername(user.getUsername());
        loginResp.setToken(token);
        return Result.success(loginResp);
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody @Valid User user){
        User username = userService.findByUsername(user.getUsername());
        boolean b = userService.findByPhone(user.getPhone());
       if (username!=null){
           return Result.error("用户已存在");
       } else if (b) {
           return Result.error("手机号已存在");
       }
        boolean flag = userService.register(user);
       if (!flag){
           return Result.error("注册失败");
       }
        return Result.success("注册成功");
    }

    @GetMapping("/profile")///查询个人信息
    public Result profile(@RequestHeader("Authorization") String token){
        String userId = jwtUtil.getClaim(token, "userId");
        return Result.success(userService.getById(userId));
    }

    @PostMapping("/updateProfile")//更新个人信息
    public Result updateProfile(@RequestBody User user,@RequestHeader("Authorization") String token){

        String userId = jwtUtil.getClaim(token, "userId");
        user.setId(Integer.parseInt(userId));
        return userService.updateById(user)?Result.success("更新成功"):Result.error("更新失败");
    }

    @PostMapping("/changePassword")
    public Result<?> changePassword(
            @RequestHeader("Authorization")String token,
            @Validated @RequestBody UpdatePasswordDTO dto) {

        // 实际项目中从Token解析用户名（这里简化为从请求头获取）
        String username = jwtUtil.getClaim(token, "username");
        if (username == null || username.isEmpty()) {
            return Result.error(401, "请先登录");
        }

        return userService.changePassword(username, dto);
    }
}
